All files / src/app/api/collections/[id]/ranking/save route.ts

100% Statements 11/11
100% Branches 4/4
100% Functions 1/1
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                    15x 15x 15x 15x 15x 15x 14x 14x 11x         3x      
import { NextRequest, NextResponse } from "next/server";
import { requireAuth } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { requireApiCollectionAccess } from "@/server/dal/collection-access";
import { RankingController } from "@/server/api/ranking";
import { errorResponse } from "@/server/api/http-errors";
 
// Save and share (spec §4.4): one transaction, idempotent on body.saveKey —
// 201 when it saved, 200 with the same link on a replay. Authz before body parse.
export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const user = await requireAuth();
    const db = getDb();
    const access = await requireApiCollectionAccess(db, id, user.id);
    if (access instanceof NextResponse) return access;
    const body: unknown = await request.json();
    const saved = await RankingController.fromDb(db).save(access.id, user.id, body);
    return NextResponse.json(
      { resultNumber: saved.result.number, shareToken: saved.shareToken },
      { status: saved.created ? 201 : 200 },
    );
  } catch (error) {
    return errorResponse(error);
  }
}